package lib.bone.admin.controller.nepu;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.constant.PostTypeConst;
import lib.bone.access.constant.UseMethodConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.access.module.post.NepuPostService;
import lib.bone.access.module.post.domain.NepuPost;
import lib.bone.access.module.userpost.NepuUserPostService;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.domain.WorkloadUseLog;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.audit.workload.service.WorkloadUseLogService;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.domain.vo.UserBaseVO;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 冲抵接口
 */
        @Slf4j
        @RestController
@RequestMapping("nepu")
@Api(tags = "工作量冲抵")
public class DeductionController {


    @Autowired
    NepuWorkloadService nepuWorkloadService;

    @Autowired
    NepuUserPostService nepuUserPostService;

    @Autowired
    NepuPostService nepuPostService;

    @Autowired
    NepuWorkloadController nepuWorkloadController;

    @Autowired
    WorkloadUseLogService logService;

    @Autowired
    SysUserService userService;


    @Autowired
    NepuCycleService cycleService;




    @GetMapping("deduction/logs")
    @ApiOperation(value = "工作量冲抵记录查询")
    public ResponseDTO<Object> userWorkloadDeductionLogs(@RequestParam(value = "userId",required = false) Long userId){
        if (Validator.isEmpty(userId))
            userId = StpUtil.getLoginIdAsLong();
        String cycleId = cycleService.getNowResearchCycleId();
        // 1. 获取抵扣记录
        List<WorkloadUseLog> useLogs = logService.findByUserIdAndCycleId(userId,cycleId);
        return ResponseDTO.succData(useLogs);
    }


    @PostMapping("deduction/cancel")
    @ApiOperation(value = "工作量冲抵取消(单用户)")
    public ResponseDTO<Object> userWorkloadDeductionCancel(@RequestParam(value = "userId",required = false) Long userId){
        if (Validator.isEmpty(userId))
            userId = StpUtil.getLoginIdAsLong();
        String cycleId = cycleService.getNowResearchCycleId();
        // 1. 获取抵扣记录
        List<WorkloadUseLog> useLogs = logService.findByUserIdAndCycleId(userId,cycleId);

        // 2. 获取工作量记录列表
        List<String> workloadIds = new ArrayList<>();

        for (WorkloadUseLog ele:useLogs){
            workloadIds.add(ele.getWorkloadId());
        }

        List<NepuWorkload> workloads = nepuWorkloadService.getByIds(workloadIds);

        // 3. 遍历并且更新记录
        workloads = workloads.stream().peek(ele->{
            for (WorkloadUseLog useLog:useLogs){
                if (ele.getId().equals(useLog.getWorkloadId())){
                    double usedWorkload = ele.getUsedWorkload();
                    //归还工作量
                    ele.setUsedWorkload(usedWorkload - useLog.getWorkload());
                    //设为未用尽
                    ele.setUsedUp(0);
                }
            }
        }).collect(Collectors.toList());

        // 4. 更新列表
        nepuWorkloadService.batchSave(workloads);

        // 5. 移除记录
        logService.deleteAll(useLogs);

        return ResponseDTO.succMsg("取消冲抵成功");
    }

    /**
     * @TODO 事务回滚 -- 不满足抵扣条件不会回滚 ? 都抵扣
     * @param userId
     * @return
     */
    @WebLog(module = "bone-system",operate = MethodTypeConst.UPDATE)
    @PostMapping("deduction")
    @ApiOperation(value = "工作量冲抵(单用户)",notes = "剩余的教学工作量直接用于计算薪酬")
    public ResponseDTO<Object> userWorkloadDeduction(@RequestParam(value = "userId",required = false) Long userId){
        if (Validator.isEmpty(userId))
            userId = StpUtil.getLoginIdAsLong();
        // 1. 获取用户岗位信息
        Optional<SysUser> userOp = userService.getById(userId);
        if (!userOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"无用户信息");
        }
        SysUser user = userOp.get();
        String postId = user.getPostId();
//        Optional<NepuUserPost> userPostOp = nepuUserPostService.findByUserId(userId);
//        if (!userPostOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"用户未绑定岗位信息");


        //String postId = userPostOp.get().getPostId();
        Optional<NepuPost> postOp = nepuPostService.getById(postId);


        if (!postOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"绑定岗位信息不存在");

        NepuPost nepuPost = postOp.get();
        // 所需工作量
        double needResearchWorkload = nepuPost.getResearchWorkload();
//        log.info("所需科研工作量:"+needResearchWorkload);
        double needTeachWorkload = nepuPost.getTeachWorkload();
//        log.info("所需教学工作量:"+needTeachWorkload);
        // 2. 查询本周期内冲抵记录
        //String cycleId = cycleService.getNowCycleId();
        String cycleId = cycleService.getNowResearchCycleId();

        List<WorkloadUseLog> useLogs = logService.findByUserIdAndCycleId(userId,cycleId);

        if (useLogs.size()!=0){
            log.info("ID:【{}】用户在本周期已经进行过冲抵",userId);
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"用户在本周期已经进行过冲抵!");
        }

        //查询管理工作量
        NepuWorkload n = new NepuWorkload(userId,WorkloadTypeConst.MANAGEMENT,0);

        Example<NepuWorkload> example = Example.of(n);



        List<NepuWorkload> nepuWorkloads = nepuWorkloadService.finAll(example);

        List<WorkloadUseLog> useLogList = new ArrayList<>();

        for (NepuWorkload nepuWorkload : nepuWorkloads) {
            if (nepuWorkload.getUsedUp()==1){
                break;
            }
            WorkloadUseLog useLog = new WorkloadUseLog();
            useLog.setUserId(nepuWorkload.getUserId());
            useLog.setWorkload(nepuWorkload.getWorkload()-nepuWorkload.getUsedWorkload());
            useLog.setWorkloadId(nepuWorkload.getId());
            useLog.setCycleId(cycleId);
            useLog.setWorkloadType(WorkloadTypeConst.MANAGEMENT);
            useLog.setUseMethod(UseMethodConst.MANAGE_SALARY);
            useLog.setWorkloadDate(nepuWorkload.getCreatedTime());
            useLogList.add(useLog);
            useLog.setLinkName("非抵扣管理工作量");
            nepuWorkload.setUsedWorkload(nepuWorkload.getWorkload());
            nepuWorkload.setUsedUp(1);
            nepuWorkloadService.updateOne(nepuWorkload);
        }
        logService.saveList(useLogList);

        // 3.查询用户未消耗完成的科研工作量，且按照等级排序
        // Sort sort = Sort.by(Sort.Direction.DESC, "workload_level");

        String postType = nepuPost.getPostType();
        log.info("岗位类型:{}",postType);

        NepuWorkload t1 = new NepuWorkload(userId,WorkloadTypeConst.RESEARCH,0);

        Example<NepuWorkload> example1 = Example.of(t1);

        // 4. 调用科研抵扣
        double r1 = nepuWorkloadService.deduction(example1,needResearchWorkload, UseMethodConst.DEDUCT_RESEARCH,postType);
        log.info("[科研工作量]调用科研抵扣后缺额:"+r1);
        // 追加分抵扣
//        NepuWorkload z1 = new NepuWorkload(userId,WorkloadTypeConst.RESEARCH_ADD,0);
//        Example<NepuWorkload> example3 = Example.of(z1);
//
//        r1 = nepuWorkloadService.deduction(example3,r1,UseMethodConst.DEDUCT_RESEARCH);

        // 5. 调用教学抵扣

        NepuWorkload t2 = new NepuWorkload(userId,WorkloadTypeConst.TEACH,0);
        // 需要对教学工作量进行周期校验，教学工作量不可结转 -- 获取当前周期
        t2.setParentId(cycleId);

        Example<NepuWorkload> example2 = Example.of(t2);

        double r2 = nepuWorkloadService.deduction(example2,needTeachWorkload, UseMethodConst.DEDUCT_TEACH,postType);
        log.info("[教学工作量]调用教学工作量抵扣后缺额:"+r2);
        // 追加分抵扣
//        NepuWorkload z2 = new NepuWorkload(userId,WorkloadTypeConst.TEACH_ADD,0);
//        // 需要对教学工作量进行周期校验，教学工作量不可结转 -- 获取当前周期
//        z2.setParentId(cycleId);
//        Example<NepuWorkload> example4 = Example.of(z2);
//
//        r2 = nepuWorkloadService.deduction(example4,r2,UseMethodConst.DEDUCT_TEACH);

        List<String> errMsgs = new ArrayList<>();

        // 6. 如果科研没有抵扣 , 根据岗位选择不同的方式

        if (PostTypeConst.TEACH.equals(postType)){
            // 教学岗位，科研工作量的 100% 用教学工作量冲抵
            r1 = nepuWorkloadService.deduction(example2,r1,UseMethodConst.DEDUCT_RESEARCH,postType);
        }else if (PostTypeConst.SYNTHESIS.equals(postType)){
            // 教学 -  研究岗位，科研工作量的 50% 可用教学工作量冲抵
            r1 = nepuWorkloadService.deduction(example2,Math.min(r1, needResearchWorkload * 0.5),UseMethodConst.DEDUCT_RESEARCH,postType);

        }else if (PostTypeConst.RESEARCH.equals(postType)){
            // 研究型岗位科研工作量不可以用教学抵扣

        }

        if (r2 > 0.0){
            log.info("ID:【{}】对应用户工作量不足以完成教学工作量抵扣",userId);
            errMsgs.add("教学冲抵工作量不足"+r2);
        }
        if (r1 > 0.0){
            log.info("ID:【{}】对应用户工作量不足以完成科研工作量抵扣",userId);
            errMsgs.add("科研冲抵工作量不足"+r1);
        }
        /**
         * 教学工作量可能存在剩余 -- 全部转化为薪酬
         */
        if (r2 == 0.0){
            double zhSum = nepuWorkloadService.convertSalary(example2,UseMethodConst.CONVERT_SALARY);
            log.info("共计:{}教学工作量结转为薪酬",zhSum);
        }


        //4.查询用户所需的科研工作量目标和教学工作量目标
        //5.选择科研工作量进行抵扣
        //若本条科研工作量记录全部使用不会超过目标科研工作量
//        for (NepuWorkload workload : researchWorkloadList) {
//            if ((workload.getWorkload() - workload.getUsedWorkload()) + researchWorkload <= researchTargetWorkload) {
//                researchWorkload += (workload.getWorkload() - workload.getUsedWorkload());
//                ResearchAttach attach = JsonUtil.string2Obj(workload.getWorkloadAttach(), ResearchAttach.class);
//                WorkloadUseLog researchTargetLog = researchUseLog(workload.getCycleId(), userId, workload.getWorkload() - workload.getUsedWorkload(), workload.getId(), WorkloadTypeConst.RESEARCH, UseMethodConst.DEDUCTRESEARCH, workload.getLinkId(), attach.getResearchName(), workload.getCreatedTime());
//                workloadUseLogList.add(researchTargetLog);
//                workload.setUsedWorkload(workload.getWorkload());
//                workload.setUsedUp(1);
//                nepuWorkloadService.updateOne(workload);
//            }
//            //若本条科研工作量记录全部使用会超过目标科研工作量
//            else {
//                ResearchAttach attach = JsonUtil.string2Obj(workload.getWorkloadAttach(), ResearchAttach.class);
//                WorkloadUseLog workloadUseLog = researchUseLog(workload.getCycleId(), workload.getUserId(), researchTargetWorkload - researchWorkload, workload.getId(), workload.getWorkloadType(), UseMethodConst.DEDUCTRESEARCH, workload.getLinkId(), attach.getResearchName(), workload.getCreatedTime());
//                workloadUseLogList.add(workloadUseLog);
//                workload.setUsedWorkload(workload.getUsedWorkload() + researchTargetWorkload - researchWorkload);
//                nepuWorkloadService.updateOne(workload);
//                researchWorkload = researchTargetWorkload;
//                break;
//            }
//
//        }
//        //6.若科研工作量已达标，就不需要抵扣
//        if (researchWorkload == researchTargetWorkload) {
//            logService.saveList(workloadUseLogList);
//            nepuWorkloadController.workloadDeduction(userId);
//            return ResponseDTO.succData(ResponseCodeConst.SUCCESS,"结算成功!");
//        }
//        //6.若科研工作量未达标，便需要抵扣
//        //计算还需要多少科研工作量能达成目标
//        Double require = researchTargetWorkload-researchWorkload;
//        double totalteachworkload = 0.0;
//        System.out.println("totalnumber:"+require);
//        //7.教学型，可以全额冲抵科研工作量
//        List<NepuWorkload> teachWorkloadList = nepuWorkloadService.findByUserIdAndWorkloadTypeAndUsedUpOrderByWorkloadAsc(userId,WorkloadTypeConst.TEACH,0);
//        if (nepuPost.getPostType().equals(PostTypeConst.TEACH)) {
//            for (NepuWorkload nepuWorkload : teachWorkloadList) {
//                totalteachworkload += nepuWorkload.getWorkload();
//            }
//            //首先判断教师的教学分是否有多余，没有多余的无法抵扣
//            nepuWorkloadController.workloadDeduction(userId);
//            if (totalteachworkload > teachTargetWorkload) {
//                //有多余的，首先完成教学工作量
//                List<NepuWorkload> workloadList = nepuWorkloadService.findByUserIdAndWorkloadTypeAndUsedUpOrderByWorkloadAsc(userId, WorkloadTypeConst.TEACH, 0);
//                double totalNumber = 0.0;
//                for (NepuWorkload nepuWorkload : workloadList) {
//                    //本条教学工作量全部冲抵科研工作量也未达标
//                    if ((nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload()) + totalNumber <= require) {
//                        totalNumber += (nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload());
//                        WorkloadUseLog researchTargetLog = teachUseLog(nepuWorkload.getCycleId(), userId, nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload(), UseMethodConst.DEDUCTRESEARCH);
//                        workloadUseLogList.add(researchTargetLog);
//                        nepuWorkload.setUsedWorkload(nepuWorkload.getWorkload());
//                        nepuWorkload.setUsedUp(1);
//                        nepuWorkloadService.updateOne(nepuWorkload);
//                    }
//                    //本条教学工作量全部冲抵科研工作量可以达标
//                    else {
//                        WorkloadUseLog researchTargetLog = teachUseLog(nepuWorkload.getCycleId(), userId, require - totalNumber, UseMethodConst.DEDUCTRESEARCH);
//                        workloadUseLogList.add(researchTargetLog);
//                        nepuWorkload.setUsedWorkload(nepuWorkload.getUsedWorkload() + require - totalNumber);
//                        nepuWorkloadService.updateOne(nepuWorkload);
//                        break;
//                    }
//
//                }
//
//            }
//            logService.saveList(workloadUseLogList);
//
//        }
//        //7.教学研究型，可以冲抵50%科研工作量
//        else if (nepuPost.getPostType().equals(PostTypeConst.SYNTHESIS)) {
//            for (NepuWorkload nepuWorkload : teachWorkloadList) {
//                totalteachworkload += nepuWorkload.getWorkload();
//            }
//            //首先判断教师的教学分是否有多余，没有多余的无法抵扣
//            nepuWorkloadController.workloadDeduction(userId);
//            if (totalteachworkload > teachTargetWorkload) {
//                //有多余的，首先完成教学工作量
//                List<NepuWorkload> workloadList = nepuWorkloadService.findByUserIdAndWorkloadTypeAndUsedUpOrderByWorkloadAsc(userId, WorkloadTypeConst.TEACH, 0);
//                double remainder = 0.0;
//                double totalNumber = 0.0;
//                double halfWorkload = researchTargetWorkload / 2;
//                //查询剩余的教学工作量是否足够科研工作量目标的一半
//                List<NepuWorkload> synthesisWorkloadList = nepuWorkloadService.findByUserIdAndWorkloadTypeAndUsedUpOrderByWorkloadAsc(userId, WorkloadTypeConst.TEACH, 0);
//                for (NepuWorkload nepuWorkload : synthesisWorkloadList) {
//                    remainder += nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload();
//                }
//                if (require > halfWorkload) {
////                if (remainder>halfWorkload){
//                    for (NepuWorkload nepuWorkload : workloadList) {
//                        //若本条教学工作量记录全部使用不会超过目标科研工作量的一半
//                        if (nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload() + totalNumber < halfWorkload) {
//                            totalNumber += (nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload());
//
//                            WorkloadUseLog teachTargetLog = teachUseLog(nepuWorkload.getCycleId(), userId, nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload(), UseMethodConst.DEDUCTRESEARCH);
//                            workloadUseLogList.add(teachTargetLog);
//                            nepuWorkload.setUsedWorkload(nepuWorkload.getWorkload());
//                            nepuWorkload.setUsedUp(1);
//                            nepuWorkloadService.updateOne(nepuWorkload);
//                        }
//                        //若本条教学工作量记录全部使用会超过目标科研工作量的一半
//                        else {
//
//                            WorkloadUseLog teachTargetLog = teachUseLog(nepuWorkload.getCycleId(), userId, halfWorkload - totalNumber, UseMethodConst.DEDUCTRESEARCH);
//                            workloadUseLogList.add(teachTargetLog);
//                            nepuWorkload.setUsedWorkload(nepuWorkload.getUsedWorkload() + halfWorkload - totalNumber);
//                            nepuWorkloadService.updateOne(nepuWorkload);
//                            break;
//
//                        }
////
//                    }
//
//                } else {
////                if (remainder>require){
//                    for (NepuWorkload nepuWorkload : workloadList) {
//                        //若本条教学工作量记录全部使用不会超过目标科研工作量
//                        if (nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload() + totalNumber < require) {
//                            totalNumber += (nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload());
//                            WorkloadUseLog teachTargetLog = teachUseLog(nepuWorkload.getCycleId(), userId, nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload(), UseMethodConst.DEDUCTRESEARCH);
//                            workloadUseLogList.add(teachTargetLog);
//                            nepuWorkload.setUsedWorkload(nepuWorkload.getWorkload());
//                            nepuWorkload.setUsedUp(1);
//                            nepuWorkloadService.updateOne(nepuWorkload);
//                        }
//                        //若本条教学工作量记录全部使用会超过目标科研工作量
//                        else {
//
//                            WorkloadUseLog teachTargetLog = teachUseLog(nepuWorkload.getCycleId(), userId, halfWorkload - totalNumber, UseMethodConst.DEDUCTRESEARCH);
//                            workloadUseLogList.add(teachTargetLog);
//                            nepuWorkload.setUsedWorkload(nepuWorkload.getUsedWorkload() + require - totalNumber);
//                            nepuWorkloadService.updateOne(nepuWorkload);
//                            break;
//                        }
//                    }
//                }
//
//            }
//            logService.saveList(workloadUseLogList);
//        }
//        //7.研究型，无法冲抵科研工作量
//        else if (nepuPost.getPostType().equals(PostTypeConst.RESEARCH)){
//            nepuWorkloadController.workloadDeduction(userId);
//            logService.saveList(workloadUseLogList);
//            return ResponseDTO.succData(ResponseCodeConst.FORBIDDEN,"研究型无法抵扣！");
//        }
        return ResponseDTO.succData(ResponseCodeConst.SUCCESS,errMsgs.toString());
    }

    @PostMapping("deduction/allUsers")
    @ApiOperation(value = "工作量冲抵(全部用户)")
    public ResponseDTO deduction(){
        List<UserBaseVO> userBaseVOS = userService.getAllUserBase();
        if (function(userBaseVOS,0)){
            return ResponseDTO.succData(ResponseCodeConst.SUCCESS,"全部用户已抵扣完成！");
        }
        return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"抵扣未完成！");
    }

    public Boolean function(List<UserBaseVO> list,Integer index){
        if (index==list.size()){
            return true;
        }
        try {
            UserBaseVO userBaseVO = list.get(index);
            if (StringUtils.isNotEmpty(userBaseVO.getPostId())){
                this.userWorkloadDeduction(userBaseVO.getId());
                log.info("ID为"+userBaseVO.getId()+"的用户成功进行抵扣！");
            }
        }catch (Exception e){
            return false;
        }
        return function(list,index+1);
    }

    @PostMapping("deductionx")
    @ApiOperation(value = "工作量冲抵(单用户)")
    public ResponseDTO<Object> deductionx(@RequestParam(value = "userId",required = false) Long userId){
        if (Validator.isEmpty(userId)){
            userId = StpUtil.getLoginIdAsLong();
        }
        // 1. 获取用户岗位信息
        Optional<SysUser> userOp = userService.getById(userId);
        if (!userOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"无用户信息");
        SysUser user = userOp.get();
        String postId = user.getPostId();
        Optional<NepuPost> postOp = nepuPostService.getById(postId);
        if (!postOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"绑定岗位信息不存在");
        NepuPost nepuPost = postOp.get();
        if (nepuPost.getPostType().equals(PostTypeConst.MANAGE)) ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"管理岗不参与绩效计算！");
        // 所需工作量
        double needResearchWorkload = nepuPost.getResearchWorkload();
        double needTeachWorkload = nepuPost.getTeachWorkload();
        // 2. 查询本周期内冲抵记录
        String cycleId = cycleService.getNowResearchCycleId();

        List<WorkloadUseLog> useLogs = logService.findByUserIdAndCycleId(userId,cycleId);

        if (useLogs.size()!=0){
            log.info("ID:【{}】用户在本周期已经进行过冲抵",userId);
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"用户在本周期已经进行过冲抵!");
        }

        // 3.查询用户未消耗完成的科研工作量，且按照等级排序

        String postType = nepuPost.getPostType();
        log.info("岗位类型:{}",postType);

        NepuWorkload t1 = new NepuWorkload(userId,WorkloadTypeConst.RESEARCH,0);

        Example<NepuWorkload> example1 = Example.of(t1);

        // 4. 调用科研抵扣
        double r1 = nepuWorkloadService.deduction(example1,needResearchWorkload, UseMethodConst.DEDUCT_RESEARCH,postType);
        log.info("[科研工作量]调用科研抵扣后缺额:"+r1);

        // 5. 调用教学抵扣
        List<NepuWorkload> list = nepuWorkloadService.findTeachAndOther(userId,0,cycleId);

        double r2 = nepuWorkloadService.deduction(list,needTeachWorkload, UseMethodConst.DEDUCT_TEACH,postType);
        log.info("[教学工作量]调用教学工作量抵扣后缺额:"+r2);

        //r1是科研缺额。r2是教学缺额
        //查询管理工作量
        NepuWorkload n = new NepuWorkload(userId,WorkloadTypeConst.MANAGE,0);

        Example<NepuWorkload> example = Example.of(n);

        List<NepuWorkload> nepuWorkloads = nepuWorkloadService.finAll(example);
        double manageSum = 0.0;
        for (NepuWorkload nepuWorkload : nepuWorkloads) {
            manageSum += nepuWorkload.getWorkload();
        }

        List<String> errMsgs = new ArrayList<>();

        // 6.教学工作量和其它有剩余，科研工作量不足的，抵扣科研
        List<NepuWorkload> list1 = nepuWorkloadService.findTeachAndOther(userId,0,cycleId);
        if (PostTypeConst.TEACH.equals(postType)){
            log.info("教学抵扣科研");
            // 教学岗位，科研工作量的 100% 用教学工作量冲抵
            r1 = nepuWorkloadService.deduction(list1,r1,UseMethodConst.DEDUCT_RESEARCH,postType);
        }else if (PostTypeConst.SYNTHESIS.equals(postType)){
            log.info("教学抵扣科研");
            // 教学 -  研究岗位，科研工作量的 50% 可用教学工作量冲抵
            r1 = nepuWorkloadService.deduction(list1,Math.min(r1, needResearchWorkload * 0.5),UseMethodConst.DEDUCT_RESEARCH,postType);

        }else if (PostTypeConst.RESEARCH.equals(postType)){
            // 研究型岗位科研工作量不可以用教学抵扣
        }
        //r1是科研缺额。r2是教学缺额
        // 6.教学工作量或科研工作量不足并且有管理工作量的，管理抵扣教学或抵扣科研（50%）
        if (manageSum != 0) {
            if (r2 > 0.0){
                log.info("管理抵扣科研");
                r2 = nepuWorkloadService.deduction(example,Math.min(r2, needTeachWorkload * 0.5),UseMethodConst.P_DEDUCT_TEACH,postType);
            }
            if (r1 > 0.0){
                log.info("管理抵扣科研");
                r1 = nepuWorkloadService.deduction(example,Math.min(r1, needResearchWorkload * 0.5),UseMethodConst.P_DEDUCT_RESEARCH,postType);
            }

        }
        if (r2 > 0.0){
            log.info("ID:【{}】对应用户工作量不足以完成教学工作量抵扣",userId);
            errMsgs.add("教学冲抵工作量不足"+r2);
        }
        if (r1 > 0.0){
            log.info("ID:【{}】对应用户工作量不足以完成科研工作量抵扣",userId);
            errMsgs.add("科研冲抵工作量不足"+r1);
        }
        /**
         * 教学工作量可能存在剩余 -- 全部转化为薪酬
         */
        List<NepuWorkload> list2 = nepuWorkloadService.findTeachAndOther(userId,0,cycleId);
        if (r2 == 0.0){
            double zhSum = nepuWorkloadService.convertSalary(list2,UseMethodConst.CONVERT_SALARY);
            log.info("共计:{}教学工作量结转为薪酬",zhSum);
        }
        double mSum = nepuWorkloadService.convertSalary(example,UseMethodConst.MANAGE_SALARY);
        log.info("共计:{}管理工作量结转为薪酬",mSum);
        return ResponseDTO.succData(ResponseCodeConst.SUCCESS,errMsgs.toString());
    }

}